import request from './request';
import storage from './storage';
import aop from './aop';
import {
  Notice,
  Message
} from 'view-design';
import config from '../utils/config';
import ErrorToolTips from '../components/ErrorToolTips';

/** 保存用户信息 */
function saveUserInfo(userInfo, persistence = true) {
  storage.setAttributeToStorage('user_info', userInfo, persistence);
}

/** 获取当前登陆人信息 */
function getUserInfo(persistence = true) {
  return storage.getAttributeFromStorage('user_info', persistence);
}

/** 保存变量到window.sessionStorage或者window.localStorage */
function setAttributeToStorage(name, value, persistence = false) {
  storage.setAttributeToStorage(name, value, persistence);
}

/** 获取cookie */
function getCookie(name) {
  return storage.getCookie(name);
}

/** 从当前会话中获取变量 */
function getAttributeFromStorage(name, persistence = false) {
  const value = storage.getAttributeFromStorage(name, persistence);
  return value;
}

/** 从本地存储中删除用户信息 */
function removeUserInfo() {
  storage.removeAttributeFromStorage('user_info');
  storage.removeAttributeFromStorage('user_info', true);
}

/** 登出 */
async function signOut() {
  const logout = config.serverProxy + config.authServicePath + '/logout';
  await getRequest(logout);
  removeUserInfo();
  storage.removeCookie('jwt');
  storage.removeCookie('token');
  storage.removeCookie('w_skey');
  storage.removeCookie('w_uid');
  storage.removeCookie('w_open_id');
  storage.removeCookie('w_expires_in');
  storage.removeCookie('wxa_session_id');
  storage.removeCookie('w_link_skey');
  storage.removeCookie('jwt', 'ybsjyyn.com');
  storage.removeCookie('w_skey', 'ybsjyyn.com');
  storage.removeCookie('w_uid', 'ybsjyyn.com');
  storage.removeCookie('w_open_id', 'ybsjyyn.com');
  storage.removeCookie('w_expires_in', 'ybsjyyn.com');
  storage.removeCookie('wxa_session_id', 'ybsjyyn.com');
  storage.removeCookie('w_link_skey', 'ybsjyyn.com');
  window.vueRouter.push('/signin');
}

async function reloadUserRole() {
  const userInfo = getUserInfo();
  if (userInfo) {
    const api = `${config.serverProxy}${config.authServicePath}/role/getMyAllRoles`;
    const response = await getRequest(api);
    if (response.data.errorCode === 0) {
      userInfo.roles = response.data.data.allRoleCodes;
      saveUserInfo(userInfo);
    }
  }
}

async function reloadUserPermission() {
  const userInfo = getUserInfo();
  if (userInfo) {
    const api = `${config.serverProxy}${config.authServicePath}/permission/getMyAllPermissions`;
    const response = await getRequest(api);
    if (response.data.errorCode === 0) {
      userInfo.permissions = response.data.data.allPermissionCodes;
      saveUserInfo(userInfo);
    }
  }
}

/** 判断用户是否已登录 */
function isAuthenticated() {
  const userInfo = getUserInfo();
  if (userInfo) {
    return true;
  } else {
    return false;
  }
}

/** 判断是否拥有权限 */
function hasPermission(permission) {
  if (!permission || permission === '')
    return true;
  else {
    /** 如果是调试模式 */
    if (config.env === 'devs') {
      return true;
    }
    const userInfo = getUserInfo();
    if (!userInfo || !userInfo.permissions) {
      return false;
    } else {
      const permissions = userInfo.permissions;
      //如果传递进来的是数组
      if (permission instanceof Array) {
        for (let i = 0; i < permission.length; i++) {
          const permissiontemp = permission[i];
          for (let h = 0; h < permissions.length; h++) {
            if (permissiontemp === permissions[h]) {
              if (i === permission.length - 1) {
                return true;
              } else {
                break;
              }
            } else {
              if (h === permissions.length - 1) {
                return false;
              }
            }
          }
        }
      }
      //如果传递进来的是字符串
      else {
        for (let f = 0; f < permissions.length; f++) {
          if (permission === permissions[f]) {
            return true;
          } else {
            if (f === permissions.length - 1) {
              return false;
            }
          }
        }
      }
    }
  }
}

/** 判断是否拥有角色 */
function hasRole(role) {
  if (!role || role === '')
    return true;
  else {
    /** 如果是调试模式 */
    if (config.env === 'dev') {
      return true;
    }
    const userInfo = getUserInfo();
    if (!userInfo || !userInfo.roles) {
      return false;
    } else {
      const roles = userInfo.roles;
      //如果传递进来的是数组
      if (role instanceof Array) {
        for (var i = 0; i < role.length; i++) {
          const roletemp = role[i];
          for (var h = 0; h < roles.length; h++) {
            if (roletemp === roles[h]) {
              if (i === role.length - 1) {
                return true;
              } else {
                break;
              }
            } else {
              if (h === roles.length - 1) {
                return false;
              }
            }
          }
        }
      }
      //如果传递进来的是字符串
      else {
        for (let h = 0; h < roles.length; h++) {
          if (role === roles[h]) {
            return true;
          } else {
            if (h === roles.length - 1) {
              return false;
            }
          }
        }
      }
    }
  }
}

function resultCheck(result) {
  result.then(response => {
    let isError = false;
    let errorMessage;
    let errorCode;
    console.log('resultCheck:',response)
    if (response.status >= 200 && response.status < 300) {
      if (parseInt(response.data.errorCode) !== 0) {
        isError = true;
        errorMessage = response.data.msg;
        errorCode = response.data.errorCode;
      }
    } else {
      isError = true;
      errorMessage = response.statusText;
      errorCode = response.status;
    }
    if (response.data.code === 0) {
      isError = false;
    }
    if (isError) {
      if (errorCode === 20002) {
        removeUserInfo();
        window.location.reload();
      } else {
        if (window !== window.top) {
          Message.error(errorMessage);
        } else {
          Notice.error({
            duration: 6,
            title: `错误代码:${errorCode}`,
            desc: errorMessage,
            render: (h) => {
              return h(ErrorToolTips, {
                props: {
                  data: {
                    errorCode,
                    errorMessage
                  }
                }
              });
            }
          });
        }
      }
    }
  });
}

/** 初始化请求时认证信息 */
function initRequestAuthInfo(config) {
  const userInfo = getUserInfo();
  if (!config) {
    config = {};
  }
  if (!config.headers) {
    config.headers = {};
  }
  if (userInfo) {
    config.headers.jwt = userInfo.jwt;
    config.headers.token = userInfo.jwt;
  }
  return config;
}

/** 发送http请求 */
function httpRequest(url, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.request(url, config);
  resultCheck(refsult);
  return refsult;
}

function getRequest(url, params, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.getRequest(url, params, config);
  resultCheck(refsult);
  return refsult;
}

function putRequest(url, data, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.putRequest(url, data, config);
  resultCheck(refsult);
  return refsult;
}

function postRequest(url, data, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.postRequest(url, data, config);
  resultCheck(refsult);
  return refsult;
}

function deleteRequest(url, params, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.deleteRequest(url, params, config);
  resultCheck(refsult);
  return refsult;
}

const webAppService = {
  /** 保存用户信息到本地存储 */
  saveUserInfo: saveUserInfo,
  /** 获取当前登陆人信息 */
  getUserInfo: getUserInfo,
  /** 从本地存储中删除用户信息 */
  removeUserInfo: removeUserInfo,
  /** 获取cookie */
  getCookie: getCookie,
  /** 发送http请求 */
  httpRequest: httpRequest,
  getRequest: getRequest,
  putRequest: putRequest,
  postRequest: postRequest,
  deleteRequest: deleteRequest,
  /** 判断是否拥有权限 */
  hasPermission: hasPermission,
  /** 判断是否拥有角色 */
  hasRole: hasRole,
  /** 判断用户是否已登录 */
  isAuthenticated: isAuthenticated,
  /** 保存变量到本窗口会话 */
  setAttributeToStorage: setAttributeToStorage,
  /** 从当前会话中获取变量 */
  getAttributeFromStorage: getAttributeFromStorage,
  /** 登出 */
  signOut: signOut,
  /** 重载用户角色 */
  reloadUserRole: reloadUserRole,
  /** 重载用户权限 */
  reloadUserPermission: reloadUserPermission
};

function beforeRequest() {
  let url = arguments[0];
  if (url.indexOf('?') !== -1) {
    url = `${url}&timestamp=${new Date().getTime()}`;
  } else {
    url = `${url}?timestamp=${new Date().getTime()}`;
  }
  arguments[0] = url;
  return arguments;
}

aop.before(webAppService, 'getRequest', beforeRequest);
aop.before(webAppService, 'putRequest', beforeRequest);
aop.before(webAppService, 'postRequest', beforeRequest);
aop.before(webAppService, 'deleteRequest', beforeRequest);

export default webAppService;
